package com.lovestudying.util;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.Vector;

import javax.imageio.ImageIO;
import javax.sql.rowset.CachedRowSet;

import com.lovestudying.entity.Course;
import com.sun.rowset.CachedRowSetImpl;

/**
 * JDBC-MYSQL数据库工具类
 * 
 * @author Administrator
 *
 */
/**
 * @author Kristina
 *
 */
/**
 * @author Kristina
 *
 */
public class DBUtil_Pro {
	// 静态常量
	private static final String DRIVER = "com.mysql.jdbc.Driver";
	private static final String URL = "jdbc:mysql://localhost:3306/studyingsystem";
	private static final String USER = "root";
	private static final String PASSWORD = "root";

	/**
	 * 连接数据库
	 * 
	 * @return 连接对象
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(DRIVER);
			conn = DriverManager.getConnection(URL, USER, PASSWORD);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 执行SELECT查询语句
	 * 
	 * @param sql
	 *            执行SQL语句
	 * @param params
	 *            SQL语句中所需参数
	 * @return 缓存结果集对象
	 */
	public static ResultSet doQuery(String sql, Vector<Object> params) {
		Connection conn = null;
		PreparedStatement ps = null;
		// 结果集
		ResultSet rs = null;
		// 缓存结果集
		CachedRowSet cachedRowSet = null;
		try {
			// 连接数据库
			conn = getConnection();
			// 创建语句对象
			ps = conn.prepareStatement(sql);
			// 通过循环可变参数数组,对?赋值
			for (int i = 0; i < params.size(); i++) {
				ps.setObject(i + 1, params.get(i)); // ps.setObject(1, 吴磊); ps.setObject(2, 男);
			}
			// 执行SQL-->得到结果集
			rs = ps.executeQuery();

			// 实例化cachedRowSet对象
			cachedRowSet = new CachedRowSetImpl();

			// void populate(ResultSet data) 将ResultSet对象中的数据存储到缓存结果集对象中
			cachedRowSet.populate(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			closeAll(rs, ps, conn);
		}
		return cachedRowSet; // 返回缓存结果集对象
	}

	/**
	 * 执行insert/update/delete语句
	 * 
	 * @param sql
	 *            执行SQL语句
	 * @param params
	 *            SQL语句中所需参数
	 * @return 影响行数
	 */
	public static int doUpdate(String sql, Vector<Object> params) {
		int n = 0;
		Connection conn = null;
		PreparedStatement ps = null;// 预编译语句对象
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < params.size(); i++) {
				ps.setObject(i + 1, params.get(i));
			}
			n = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭
			closeAll(null, ps, conn);
		}
		return n;
	}

	/**
	 * 关闭数据库资源
	 * 
	 * @param rs
	 * @param ps
	 * @param conn
	 */
	public static void closeAll(ResultSet rs, PreparedStatement ps, Connection conn) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭数据库资源
	 * 
	 * @param ps
	 * @param conn
	 */
	public static void closeAll(PreparedStatement ps, Connection conn) {
		try {
			if (ps != null) {
				ps.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 生成现在的时间戳，可直接将timestamp直接编译进预编译语句
	 * 
	 * @return Timestamp
	 */
	public static String GetNowTime() {
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String format = simpleDateFormat.format(date);
		return format;
	}

	/**
	 * 随机生成字符串
	 * 
	 * @param length
	 *            设定字符串长度
	 * @return 返回随机生成的字符串
	 */
	public static String getRandomString(int length) {
		String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(62);
			sb.append(str.charAt(number));
		}
		return sb.toString();
	}

	/**
	 * 转换为YYYY-MM-DD格式的date
	 * 
	 * @param dateStr
	 *            YY-MM-DD格式的日期字符串
	 * 
	 * @return 对应的date类型
	 */
	// public static Date setString2SQLDate(String dateStr) {
	// SimpleDateFormat dateFormatHiddenHour = new SimpleDateFormat("yyyy-MM-dd");
	// Date date = null;
	// try {
	// String s = dateFormatHiddenHour.format(dateFormatHiddenHour.parse(dateStr));
	// date = Date.parse(s);
	// } catch (ParseException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	//
	// }
	// return date;
	// }

	public static String GetUUID() {
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		return uuid;
	}

	/**
	 * 根据预编译语句和参数执行
	 * 
	 * @param sql
	 * @param params
	 * @return
	 */
	// public static ResultSet DoQuerryByparam(StringBuffer sql, Vector<Object>
	// params) {
	// ResultSet rs = null;
	// switch (params.size()) {
	// case 0:
	// rs = DBUtil_Pro.doQuery(sql.toString());
	// break;
	// case 1:
	// rs = DBUtil_Pro.doQuery(sql.toString(), params.get(0));
	// break;
	// case 2:
	// rs = DBUtil_Pro.doQuery(sql.toString(), params.get(0), params.get(1));
	// break;
	// case 3:
	// rs = DBUtil_Pro.doQuery(sql.toString(), params.get(0), params.get(1),
	// params.get(2));
	// break;
	// case 4:
	// rs = DBUtil_Pro.doQuery(sql.toString(), params.get(0), params.get(1),
	// params.get(2), params.get(3));
	// break;
	// case 5:
	// rs = DBUtil_Pro.doQuery(sql.toString(), params.get(0), params.get(1),
	// params.get(2), params.get(3),
	// params.get(4));
	// break;
	// case 6:
	// rs = DBUtil_Pro.doQuery(sql.toString(), params.get(0), params.get(1),
	// params.get(2), params.get(3),
	// params.get(4), params.get(5));
	// break;
	// case 7:
	// rs = DBUtil_Pro.doQuery(sql.toString(), params.get(0), params.get(1),
	// params.get(2), params.get(3),
	// params.get(4), params.get(5), params.get(6));
	// break;
	// default:
	// break;
	// }
	// return rs;
	// }

	/**
	 * @param plainText
	 *            加密的字符串
	 * @return 加密后的字符串
	 */
	public static String getMd5(String plainText) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			// 32位加密
			return buf.toString();
			// 16位的加密
			// return buf.toString().substring(8, 24);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 缩放后裁剪图片方法
	 * 
	 * @param srcImageFile
	 *            源文件
	 * @param x
	 *            x坐标
	 * @param y
	 *            y坐标
	 * @param destWidth
	 *            最终生成的图片宽
	 * @param destHeight
	 *            最终生成的图片高
	 * @param finalWidth
	 *            缩放宽度
	 * @param finalHeight
	 *            缩放高度
	 */
	public static void abscut(String srcImageFile, Integer x, Integer y, Integer destWidth, Integer destHeight,
			Integer finalWidth, Integer finalHeight) {
		if (finalWidth != 0 && finalHeight != 0) {
			try {
				Image img;
				ImageFilter cropFilter;
				// 读取源图像
				BufferedImage bi = ImageIO.read(new File(srcImageFile));
				int srcWidth = bi.getWidth(); // 源图宽度
				int srcHeight = bi.getHeight(); // 源图高度

				if (srcWidth >= destWidth && srcHeight >= destHeight) {
					Image image = bi.getScaledInstance(finalWidth, finalHeight, Image.SCALE_DEFAULT);// 获取缩放后的图片大小
					cropFilter = new CropImageFilter(x, y, destWidth, destHeight);
					img = Toolkit.getDefaultToolkit()
							.createImage(new FilteredImageSource(image.getSource(), cropFilter));
					BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
					Graphics g = tag.getGraphics();
					g.drawImage(img, 0, 0, null); // 绘制截取后的图
					g.dispose();
					// 输出为文件
					ImageIO.write(tag, "JPEG", new File(srcImageFile));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static <T> List<T> GetRandomInfoList(List<T> list, Integer count) {
		List<T> newList = new ArrayList<T>();
		Random r = new Random();
		for (int i = 0; i < count; i++) {
			if (list.size() == 0) {
				return newList;
			}
			int ran1 = r.nextInt(list.size());
			newList.add(list.get(ran1));
			list.remove(ran1);
		}
		return newList;

	}
}
